package com.qs.dao;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.infomanage.bean.FieldBean;
import com.infomanage.bean.SearchBean;
import com.infomanage.dao.BaseDAO;
import com.infomanage.exception.DaoException;
import com.infomanage.po.HibernateSessionFactory;
import com.qs.po.QsEquClass;
import com.qs.po.QsEquEntry;
import com.qs.vo.QsEquEntryItem;

public class QsEquEntryDAO extends BaseDAO<QsEquEntry>{
	public QsEquEntryItem find(int id) throws DaoException{
		try {
			SearchBean searchBean  = new SearchBean();
			FieldBean fieldBean  = new FieldBean();
			fieldBean.setName("id");
			fieldBean.setValue(id);
			searchBean.add(fieldBean);
			List result = super.findByFields(new Class[] { QsEquClass.class },
					QsEquEntry.class, new String[] { "id"},
					new String[] { "classId"}, searchBean);
			List<QsEquEntryItem> items = parseResult(result);
			return items.size() == 0 ? null : items.get(0);
		} catch (Exception e) {
			throw new DaoException(e);
		} finally {
			HibernateSessionFactory.closeSession();
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<QsEquEntryItem> findAll() throws DaoException {
		try {
			List result = findAllMutilTable(new Class[] { QsEquClass.class },
					QsEquEntry.class, new String[] { "id"},
					new String[] { "classId"});
			return parseResult(result);
		} catch (Exception e) {
			throw new DaoException(e);
		} finally {
			HibernateSessionFactory.closeSession();
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<QsEquEntryItem> findByFields(SearchBean searchBean) throws DaoException {
		List result = super.findByFields(new Class[] { QsEquClass.class },
				QsEquEntry.class, new String[] { "id"},
				new String[] { "classId"}, searchBean);
		return parseResult(result);
	}
	
	@SuppressWarnings("unchecked")
	public List<QsEquEntryItem> findByClass(int classId) throws DaoException {
		SearchBean searchBean = new SearchBean();
		FieldBean fieldBean = new FieldBean();
		fieldBean.setName("classId");
		fieldBean.setValue(classId);
		searchBean.add(fieldBean);
		List result = super.findByFields(new Class[] { QsEquClass.class },
				QsEquEntry.class, new String[] { "id"},
				new String[] { "classId"}, searchBean);
		return parseResult(result);
	}
	
	
	public List<QsEquEntryItem> parseResult(List result){
		Iterator it = result.iterator();
		List<QsEquEntryItem> list = new ArrayList<QsEquEntryItem>();
		while (it.hasNext()) {
			Object[] o = (Object[]) it.next();
			QsEquEntry bean = (QsEquEntry) o[0];
			QsEquClass equClass = (QsEquClass) o[1];
			QsEquEntryItem item = new QsEquEntryItem();
			item.setBean(bean);
			item.setEquClass(equClass);
			list.add(item);
		}
		return list;
	}
	
	public int count(SearchBean searchBean){
		return super.count(new Class[] { QsEquClass.class },
				QsEquEntry.class, new String[] { "id"},
				new String[] { "classId"}, searchBean);
	}
}
